'use client';
import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Tag,
  Modal,
  Form,
  message,
  Typography,
  Divider,
  Row,
  Col,
  Space,
  DatePicker,
  Tabs,
  Badge
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, FilterOutlined, UserOutlined, LoginOutlined, SecurityScanOutlined, InfoCircleOutlined, ExclamationCircleOutlined, AlertOutlined } from '@ant-design/icons';
import { systemLogService } from '../../service/system-log.service';

const { Title, Text, Paragraph } = Typography;
// Search 已替换为 Space.Compact 实现
const { Option } = Select;
const { RangePicker } = DatePicker;


// 操作类型定义
const OPERATION_TYPES = {
  CREATE: 'create',
  UPDATE: 'update',
  DELETE: 'delete',
  PUBLISH: 'publish',
  REVIEW: 'review',
  LOGIN: 'login',
  LOGOUT: 'logout',
  SETTING: 'setting',
  IMPORT: 'import',
  EXPORT: 'export'
};

// 操作类型映射
const operationTypeMap: Record<string, { label: string; color: string }> = {
  [OPERATION_TYPES.CREATE]: { label: '创建', color: 'green' },
  [OPERATION_TYPES.UPDATE]: { label: '更新', color: 'blue' },
  [OPERATION_TYPES.DELETE]: { label: '删除', color: 'red' },
  [OPERATION_TYPES.PUBLISH]: { label: '发布', color: 'orange' },
  [OPERATION_TYPES.REVIEW]: { label: '审核', color: 'purple' },
  [OPERATION_TYPES.LOGIN]: { label: '登录', color: 'cyan' },
  [OPERATION_TYPES.LOGOUT]: { label: '登出', color: 'lime' },
  [OPERATION_TYPES.SETTING]: { label: '设置', color: 'geekblue' },
  [OPERATION_TYPES.IMPORT]: { label: '导入', color: 'magenta' },
  [OPERATION_TYPES.EXPORT]: { label: '导出', color: 'volcano' }
};

// 安全事件级别
const SECURITY_LEVELS = {
  INFO: 'info',
  WARNING: 'warning',
  ERROR: 'error',
  CRITICAL: 'critical'
};

// 安全事件级别映射
const securityLevelMap: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
  [SECURITY_LEVELS.INFO]: { label: '信息', color: 'blue', icon: <InfoCircleOutlined /> },
  [SECURITY_LEVELS.WARNING]: { label: '警告', color: 'orange', icon: <ExclamationCircleOutlined /> },
  [SECURITY_LEVELS.ERROR]: { label: '错误', color: 'red', icon: <AlertOutlined /> },
  [SECURITY_LEVELS.CRITICAL]: { label: '严重', color: 'volcano', icon: <SecurityScanOutlined /> }
};

// 登录结果
const LOGIN_RESULT = {
  SUCCESS: 'success',
  FAILURE: 'failure',
  LOCKED: 'locked'
};

// 登录结果映射
const loginResultMap: Record<string, { label: string; color: string }> = {
  [LOGIN_RESULT.SUCCESS]: { label: '成功', color: 'green' },
  [LOGIN_RESULT.FAILURE]: { label: '失败', color: 'red' },
  [LOGIN_RESULT.LOCKED]: { label: '锁定', color: 'volcano' }
};

interface AdminOperation {
  id: number;
  adminId: number;
  adminName: string;
  operationType: string;
  targetType: string;
  targetId?: number;
  targetName: string;
  operationDetails: string;
  ipAddress: string;
  userAgent: string;
  createdAt: string;
  status: string;
}

interface LoginLog {
  id: number;
  adminId: number;
  adminName: string;
  loginTime: string;
  ipAddress: string;
  userAgent: string;
  loginResult: string;
  failureReason?: string;
  location: string;
  deviceInfo: string;
}

interface SecurityEvent {
  id: number;
  eventType: string;
  eventLevel: string;
  description: string;
  affectedUser?: string;
  affectedResource?: string;
  occurrenceTime: string;
  ipAddress: string;
  status: string;
  resolution?: string;
  isRead: boolean;
}

const LogManagement: React.FC = () => {
  // 状态定义
  const [adminOperations, setAdminOperations] = useState<AdminOperation[]>([]);
  const [filteredOperations, setFilteredOperations] = useState<AdminOperation[]>([]);
  const [loginLogs, setLoginLogs] = useState<LoginLog[]>([]);
  const [filteredLoginLogs, setFilteredLoginLogs] = useState<LoginLog[]>([]);
  const [securityEvents, setSecurityEvents] = useState<SecurityEvent[]>([]);
  const [filteredSecurityEvents, setFilteredSecurityEvents] = useState<SecurityEvent[]>([]);
  
  // 统计数据状态
  const [statistics, setStatistics] = useState({
    totalOperations: 0,
    totalLogins: 0,
    failedLogins: 0,
    securityEventsCount: 0,
    unreadSecurityEvents: 0,
    criticalEvents: 0
  });
  
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [selectedOperationType, setSelectedOperationType] = useState<string>('all');
  const [selectedAdmin, setSelectedAdmin] = useState<string>('all');
  const [selectedLoginResult, setSelectedLoginResult] = useState<string>('all');
  const [selectedSecurityLevel, setSelectedSecurityLevel] = useState<string>('all');
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);
  const [loginDateRange, setLoginDateRange] = useState<[string, string] | null>(null);
  const [securityDateRange, setSecurityDateRange] = useState<[string, string] | null>(null);
  
  // 获取管理员列表（用于筛选）
  const [admins, setAdmins] = useState<Array<{ id: number; name: string }>>([]);

  // 生成随机IP地址
  const generateIPAddress = () => {
    return `${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`;
  };
  
  // 生成随机用户代理
  const generateUserAgent = () => {
    const agents = [
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15',
      'Mozilla/5.0 (iPhone; CPU iPhone OS 15_5 like Mac OS X) AppleWebKit/605.1.15',
      'Mozilla/5.0 (Linux; Android 12; SM-G991U) AppleWebKit/537.36'
    ];
    return agents[Math.floor(Math.random() * agents.length)];
  };
  
  // 生成过去30天的日期
  const getRandomDateInLast30Days = () => {
    const date = new Date();
    date.setDate(date.getDate() - Math.floor(Math.random() * 30));
    return date.toISOString();
  };

  // 获取管理员操作日志
  const fetchAdminOperations = async (params?: any) => {
    try {
      setLoading(true);
      const response = await systemLogService.getAdminOperations(params);
      const data = (response as any)?.data || response || [];
      setAdminOperations(data.map(item => ({
        ...item,
        adminName: item.username || 'unknown'
      })));
      setFilteredOperations(data.map(item => ({
        ...item,
        status: item.status || 'unknown',
        adminName: item.username || 'unknown'
      })));
    } catch (error) {
      console.error('获取管理员操作日志失败:', error);
      message.error('获取管理员操作日志失败');
      // 如果API调用失败，使用模拟数据作为降级方案
      generateMockAdminOperations();
    } finally {
      setLoading(false);
    }
  };

  // 获取登录日志
  const fetchLoginLogs = async (params?: any) => {
    try {
      setLoading(true);
      const response = await systemLogService.getLoginLogs(params);
      const data = (response as any)?.data || response || [];
      setLoginLogs(data);
      setFilteredLoginLogs(data);
    } catch (error) {
      console.error('获取登录日志失败:', error);
      message.error('获取登录日志失败');
      // 如果API调用失败，使用模拟数据作为降级方案
      generateMockLoginLogs();
    } finally {
      setLoading(false);
    }
  };

  // 获取安全事件
  const fetchSecurityEvents = async (params?: any) => {
    try {
      setLoading(true);
      const response = await systemLogService.getSecurityEvents(params);
      const data = (response as any)?.data || response || [];
      setSecurityEvents(data);
      setFilteredSecurityEvents(data);
    } catch (error) {
      console.error('获取安全事件失败:', error);
      message.error('获取安全事件失败');
      // 如果API调用失败，使用模拟数据作为降级方案
      generateMockSecurityEvents();
    } finally {
      setLoading(false);
    }
  };

  // 获取统计数据
  const fetchStatistics = async () => {
    try {
      const response = await systemLogService.getStatistics();
      const statsData = (response as any)?.data || response || {};
      
      // 设置统计数据状态
      setStatistics({
        totalOperations: statsData.totalOperations || adminOperations.length,
        totalLogins: statsData.totalLogins || loginLogs.length,
        failedLogins: statsData.failedLogins || loginLogs.filter(log => log.loginResult === LOGIN_RESULT.FAILURE).length,
        securityEventsCount: statsData.securityEventsCount || securityEvents.length,
        unreadSecurityEvents: statsData.unreadSecurityEvents || securityEvents.filter(event => !event.isRead).length,
        criticalEvents: statsData.criticalEvents || securityEvents.filter(event => event.eventLevel === SECURITY_LEVELS.CRITICAL).length
      });
      
      return statsData;
    } catch (error) {
      console.error('获取统计数据失败:', error);
      // 如果API调用失败，基于现有数据计算统计数据
      const fallbackStats = {
        totalOperations: adminOperations.length,
        totalLogins: loginLogs.length,
        failedLogins: loginLogs.filter(log => log.loginResult === LOGIN_RESULT.FAILURE).length,
        securityEventsCount: securityEvents.length,
        unreadSecurityEvents: securityEvents.filter(event => !event.isRead).length,
        criticalEvents: securityEvents.filter(event => event.eventLevel === SECURITY_LEVELS.CRITICAL).length
      };
      setStatistics(fallbackStats);
      return fallbackStats;
    }
  };

  // 初始数据加载useEffect
  useEffect(() => {
    const loadInitialData = async () => {
      setLoading(true);
      try {
        await Promise.allSettled([
          fetchAdminOperations(),
          fetchLoginLogs(),
          fetchSecurityEvents()
        ]);
        // 获取统计数据
        await fetchStatistics();
      } catch (error) {
        console.error('加载数据失败:', error);
        // 如果API调用失败，生成模拟数据作为降级方案
        generateMockAdminOperations();
        generateMockLoginLogs();
        generateMockSecurityEvents();
        // 生成模拟数据后重新计算统计数据
        await fetchStatistics();
      } finally {
        setLoading(false);
      }
    };

    loadInitialData();
  }, []);

  // 生成模拟数据函数（作为降级方案）
  const generateMockAdminOperations = () => {
    // 生成模拟管理员数据
    const mockAdmins = Array.from({ length: 10 }, (_, index) => ({
      id: index + 1,
      name: `管理员${index + 1}`
    }));
    setAdmins(mockAdmins);
    
    // 生成模拟管理员操作记录
    const mockOperations: AdminOperation[] = Array.from({ length: 300 }, (_, index) => {
      const operationTypes = Object.values(OPERATION_TYPES);
      const targetTypes = ['文章', '用户', '分类', '标签', '评论', '系统设置'];
      const operationType = operationTypes[Math.floor(Math.random() * operationTypes.length)];
      const targetType = targetTypes[Math.floor(Math.random() * targetTypes.length)];
      const admin = mockAdmins[Math.floor(Math.random() * mockAdmins.length)];
      
      let details = '';
      let targetName = '';
      
      switch (operationType) {
        case OPERATION_TYPES.CREATE:
          targetName = `${targetType}${index + 1}`;
          details = `创建了${targetType}: ${targetName}`;
          break;
        case OPERATION_TYPES.UPDATE:
          targetName = `${targetType}${Math.floor(Math.random() * 50) + 1}`;
          details = `更新了${targetType}: ${targetName}`;
          break;
        case OPERATION_TYPES.DELETE:
          targetName = `${targetType}${Math.floor(Math.random() * 50) + 1}`;
          details = `删除了${targetType}: ${targetName}`;
          break;
        case OPERATION_TYPES.PUBLISH:
          targetName = `文章${Math.floor(Math.random() * 50) + 1}`;
          details = `发布了文章: ${targetName}`;
          break;
        case OPERATION_TYPES.REVIEW:
          targetName = `评论${Math.floor(Math.random() * 100) + 1}`;
          details = `审核了评论: ${targetName}`;
          break;
        default:
          targetName = `${targetType}${Math.floor(Math.random() * 50) + 1}`;
          details = `${operationTypeMap[operationType]?.label || operationType}了${targetType}: ${targetName}`;
      }
      
      return {
        id: index + 1,
        adminId: admin.id,
        adminName: admin.name,
        operationType,
        targetType,
        targetId: Math.floor(Math.random() * 100) + 1,
        targetName,
        operationDetails: details,
        ipAddress: generateIPAddress(),
        userAgent: generateUserAgent(),
        createdAt: getRandomDateInLast30Days(),
        status: Math.random() > 0.05 ? 'success' : 'failed'
      };
    });
    
    setAdminOperations(mockOperations);
    setFilteredOperations(mockOperations);
  };

  const generateMockLoginLogs = () => {
    // 生成模拟登录日志
    const mockAdmins = Array.from({ length: 10 }, (_, index) => ({
      id: index + 1,
      name: `管理员${index + 1}`
    }));

    const mockLoginLogs: LoginLog[] = Array.from({ length: 200 }, (_, index) => {
      const admin = mockAdmins[Math.floor(Math.random() * mockAdmins.length)];
      const loginResult = Math.random() > 0.1 ? LOGIN_RESULT.SUCCESS : 
                          Math.random() > 0.5 ? LOGIN_RESULT.FAILURE : LOGIN_RESULT.LOCKED;
      
      const locations = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安', '南京', '海外'];
      const deviceInfos = ['Chrome/Windows', 'Safari/MacOS', 'Firefox/Windows', 'Edge/Windows', '移动端'];
      
      let failureReason = undefined;
      if (loginResult === LOGIN_RESULT.FAILURE) {
        const reasons = ['密码错误', '账号不存在', '验证码错误', 'IP限制'];
        failureReason = reasons[Math.floor(Math.random() * reasons.length)];
      }
      
      return {
        id: index + 1,
        adminId: admin.id,
        adminName: admin.name,
        loginTime: getRandomDateInLast30Days(),
        ipAddress: generateIPAddress(),
        userAgent: generateUserAgent(),
        loginResult,
        failureReason,
        location: locations[Math.floor(Math.random() * locations.length)],
        deviceInfo: deviceInfos[Math.floor(Math.random() * deviceInfos.length)]
      };
    });
    
    setLoginLogs(mockLoginLogs);
    setFilteredLoginLogs(mockLoginLogs);
  };

  const generateMockSecurityEvents = () => {
    // 生成模拟安全事件
    const mockAdmins = Array.from({ length: 10 }, (_, index) => ({
      id: index + 1,
      name: `管理员${index + 1}`
    }));

    const mockSecurityEvents: SecurityEvent[] = Array.from({ length: 150 }, (_, index) => {
      const eventLevels = Object.values(SECURITY_LEVELS);
      const eventTypes = ['登录失败', '权限提升', '数据访问', '配置修改', '系统异常', 'IP封禁', '暴力破解', '异常行为'];
      
      const eventType = eventTypes[Math.floor(Math.random() * eventTypes.length)];
      const eventLevel = eventTypes.includes(eventType) && (eventType === '暴力破解' || eventType === '权限提升') 
                        ? SECURITY_LEVELS.CRITICAL 
                        : eventTypes.includes(eventType) && (eventType === '登录失败' || eventType === 'IP封禁')
                        ? SECURITY_LEVELS.WARNING
                        : eventLevels[Math.floor(Math.random() * eventLevels.length)];
      
      const descriptions = [
        `${eventType}事件检测`,
        `检测到${eventType}尝试`,
        `${eventType}行为分析`,
        `${eventType}风险预警`
      ];
      
      return {
        id: index + 1,
        eventType,
        eventLevel,
        description: descriptions[Math.floor(Math.random() * descriptions.length)],
        affectedUser: Math.random() > 0.3 ? mockAdmins[Math.floor(Math.random() * mockAdmins.length)].name : undefined,
        affectedResource: Math.random() > 0.4 ? `资源${Math.floor(Math.random() * 50) + 1}` : undefined,
        occurrenceTime: getRandomDateInLast30Days(),
        ipAddress: generateIPAddress(),
        status: Math.random() > 0.2 ? 'resolved' : 'pending',
        resolution: Math.random() > 0.3 ? '已处理' : undefined,
        isRead: Math.random() > 0.3
      };
    });
    
    setSecurityEvents(mockSecurityEvents);
    setFilteredSecurityEvents(mockSecurityEvents);
  };

  // 筛选管理员操作记录
  useEffect(() => {
    let result = [...adminOperations];
    
    // 按操作类型筛选
    if (selectedOperationType !== 'all') {
      result = result.filter(op => op.operationType === selectedOperationType);
    }
    
    // 按管理员筛选
    if (selectedAdmin !== 'all') {
      result = result.filter(op => op.adminId.toString() === selectedAdmin);
    }
    
    // 按日期范围筛选
    if (dateRange && dateRange[0] && dateRange[1]) {
      const startDate = new Date(dateRange[0]);
      const endDate = new Date(dateRange[1]);
      endDate.setHours(23, 59, 59, 999);
      
      result = result.filter(op => {
        const opDate = new Date(op.createdAt);
        return opDate >= startDate && opDate <= endDate;
      });
    }
    
    // 按搜索文本筛选
    if (searchText) {
      const lowerSearchText = searchText.toLowerCase();
      result = result.filter(op => 
        op.adminName.toLowerCase().includes(lowerSearchText) ||
        op.targetName.toLowerCase().includes(lowerSearchText) ||
        op.operationDetails.toLowerCase().includes(lowerSearchText) ||
        op.ipAddress.toLowerCase().includes(lowerSearchText)
      );
    }
    
    // 按时间倒序排列
    result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
    
    setFilteredOperations(result);
  }, [adminOperations, searchText, selectedOperationType, selectedAdmin, dateRange]);

  // 筛选登录日志
  useEffect(() => {
    let result = [...loginLogs];
    
    // 按登录结果筛选
    if (selectedLoginResult !== 'all') {
      result = result.filter(log => log.loginResult === selectedLoginResult);
    }
    
    // 按管理员筛选
    if (selectedAdmin !== 'all') {
      result = result.filter(log => log.adminId.toString() === selectedAdmin);
    }
    
    // 按日期范围筛选
    if (loginDateRange && loginDateRange[0] && loginDateRange[1]) {
      const startDate = new Date(loginDateRange[0]);
      const endDate = new Date(loginDateRange[1]);
      endDate.setHours(23, 59, 59, 999);
      
      result = result.filter(log => {
        const logDate = new Date(log.loginTime);
        return logDate >= startDate && logDate <= endDate;
      });
    }
    
    // 按搜索文本筛选
    if (searchText) {
      const lowerSearchText = searchText.toLowerCase();
      result = result.filter(log => 
        log.adminName.toLowerCase().includes(lowerSearchText) ||
        log.ipAddress.toLowerCase().includes(lowerSearchText) ||
        log.location.toLowerCase().includes(lowerSearchText) ||
        (log.failureReason && log.failureReason.toLowerCase().includes(lowerSearchText))
      );
    }
    
    // 按时间倒序排列
    result.sort((a, b) => new Date(b.loginTime).getTime() - new Date(a.loginTime).getTime());
    
    setFilteredLoginLogs(result);
  }, [loginLogs, searchText, selectedLoginResult, selectedAdmin, loginDateRange]);

  // 筛选安全事件
  useEffect(() => {
    let result = [...securityEvents];
    
    // 按安全级别筛选
    if (selectedSecurityLevel !== 'all') {
      result = result.filter(event => event.eventLevel === selectedSecurityLevel);
    }
    
    // 按日期范围筛选
    if (securityDateRange && securityDateRange[0] && securityDateRange[1]) {
      const startDate = new Date(securityDateRange[0]);
      const endDate = new Date(securityDateRange[1]);
      endDate.setHours(23, 59, 59, 999);
      
      result = result.filter(event => {
        const eventDate = new Date(event.occurrenceTime);
        return eventDate >= startDate && eventDate <= endDate;
      });
    }
    
    // 按搜索文本筛选
    if (searchText) {
      const lowerSearchText = searchText.toLowerCase();
      result = result.filter(event => 
        event.eventType.toLowerCase().includes(lowerSearchText) ||
        event.description.toLowerCase().includes(lowerSearchText) ||
        event.ipAddress.toLowerCase().includes(lowerSearchText) ||
        (event.affectedUser && event.affectedUser.toLowerCase().includes(lowerSearchText)) ||
        (event.affectedResource && event.affectedResource.toLowerCase().includes(lowerSearchText))
      );
    }
    
    // 按时间倒序排列
    result.sort((a, b) => new Date(b.occurrenceTime).getTime() - new Date(a.occurrenceTime).getTime());
    
    setFilteredSecurityEvents(result);
  }, [securityEvents, searchText, selectedSecurityLevel, securityDateRange]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 处理日期范围变化
  const handleDateRangeChange = (dates: any, dateStrings: [string, string]) => {
    setDateRange(dateStrings);
  };

  const handleLoginDateRangeChange = (dates: any, dateStrings: [string, string]) => {
    setLoginDateRange(dateStrings);
  };

  const handleSecurityDateRangeChange = (dates: any, dateStrings: [string, string]) => {
    setSecurityDateRange(dateStrings);
  };

  // 标记安全事件为已读
  const handleMarkAsRead = (id: number) => {
    const updatedEvents = securityEvents.map(event => 
      event.id === id ? { ...event, isRead: true } : event
    );
    setSecurityEvents(updatedEvents);
  };

  // 处理安全事件解决
  const handleResolveEvent = (id: number) => {
    const updatedEvents = securityEvents.map(event => 
      event.id === id ? { ...event, status: 'resolved', resolution: '已处理', isRead: true } : event
    );
    setSecurityEvents(updatedEvents);
    message.success('安全事件已标记为已解决');
  };

  // 计算统计数据（从状态获取）
  const { totalOperations, totalLogins, failedLogins, securityEventsCount, unreadSecurityEvents, criticalEvents } = statistics;

  // 管理员操作记录列表列配置
  const operationColumns: ColumnsType<AdminOperation> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '操作人',
      dataIndex: 'adminName',
      key: 'adminName',
      width: 120
    },
    {
      title: '操作类型',
      dataIndex: 'operationType',
      key: 'operationType',
      width: 100,
      render: (type: string) => (
        <Tag color={operationTypeMap[type]?.color}>
          {operationTypeMap[type]?.label}
        </Tag>
      )
    },
    {
      title: '操作对象',
      key: 'target',
      render: (record: AdminOperation) => `${record.targetType}: ${record.targetName}`,
      width: 180
    },
    {
      title: '操作详情',
      dataIndex: 'operationDetails',
      key: 'operationDetails'
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      width: 150
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>
          {status === 1 ? '成功' : '失败'}
        </Tag>
      )
    },
    {
      title: '操作时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString()
    }
  ];

  // 登录日志列表列配置
  const loginLogColumns: ColumnsType<LoginLog> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '管理员',
      dataIndex: 'adminName',
      key: 'adminName',
      width: 120
    },
    {
      title: '登录时间',
      dataIndex: 'loginTime',
      key: 'loginTime',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      width: 150
    },
    {
      title: '登录地点',
      dataIndex: 'location',
      key: 'location',
      width: 100
    },
    {
      title: '设备信息',
      dataIndex: 'deviceInfo',
      key: 'deviceInfo',
      width: 150
    },
    {
      title: '登录结果',
      dataIndex: 'loginResult',
      key: 'loginResult',
      width: 100,
      render: (result: string) => (
        <Tag color={loginResultMap[result]?.color}>
          {loginResultMap[result]?.label}
        </Tag>
      )
    },
    {
      title: '失败原因',
      dataIndex: 'failureReason',
      key: 'failureReason',
      render: (reason?: string) => reason || '-'
    }
  ];

  // 安全事件列表列配置
  const securityEventColumns: ColumnsType<SecurityEvent> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      render: (id: number, record: SecurityEvent) => (
        <div>
          {id}
          {!record.isRead && <Badge dot color="red" style={{ marginLeft: '4px' }} />}
        </div>
      )
    },
    {
      title: '事件类型',
      dataIndex: 'eventType',
      key: 'eventType',
      width: 120
    },
    {
      title: '事件级别',
      dataIndex: 'eventLevel',
      key: 'eventLevel',
      width: 100,
      render: (level: string) => (
        <Tag icon={securityLevelMap[level]?.icon} color={securityLevelMap[level]?.color}>
          {securityLevelMap[level]?.label}
        </Tag>
      )
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      render: (desc: string, record: SecurityEvent) => (
        <div style={{ fontWeight: record.isRead ? 'normal' : 'bold' }}>
          {desc}
        </div>
      )
    },
    {
      title: '影响用户',
      dataIndex: 'affectedUser',
      key: 'affectedUser',
      render: (user?: string) => user || '-',
      width: 120
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      width: 150
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={status === 'resolved' ? 'green' : 'orange'}>
          {status === 'resolved' ? '已解决' : '待处理'}
        </Tag>
      )
    },
    {
      title: '发生时间',
      dataIndex: 'occurrenceTime',
      key: 'occurrenceTime',
      width: 180,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record: SecurityEvent) => (
        <Space size="middle">
          {!record.isRead && (
            <Button size="small" onClick={() => handleMarkAsRead(record.id)}>
              标记已读
            </Button>
          )}
          {record.status === 'pending' && (
            <Button size="small" type="primary" onClick={() => handleResolveEvent(record.id)}>
              标记解决
            </Button>
          )}
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Title level={3}>操作日志</Title>
      
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card title="操作统计" variant="outlined">
            <div style={{ marginBottom: '16px' }}>
              <Text strong>总操作次数：</Text>
              <Text type="secondary">{totalOperations} 次</Text>
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Text strong>登录次数：</Text>
              <Text type="secondary">{totalLogins} 次</Text>
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Text strong>失败登录：</Text>
              <Text type="danger">{failedLogins} 次</Text>
            </div>
          </Card>
        </Col>
        <Col span={6}>
          <Card title="安全事件" variant="outlined">
            <div style={{ marginBottom: '16px' }}>
              <Text strong>事件总数：</Text>
              <Text type="secondary">{securityEventsCount} 起</Text>
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Text strong>未读事件：</Text>
              <Text type="warning">{unreadSecurityEvents} 起</Text>
            </div>
            <div style={{ marginBottom: '16px' }}>
              <Text strong>严重事件：</Text>
              <Text type="danger">{criticalEvents} 起</Text>
            </div>
          </Card>
        </Col>
      </Row>
      
      <Tabs 
        defaultActiveKey="1" 
        type="card"
        items={[
          {
            key: '1',
            label: <span><UserOutlined /> 管理员操作记录</span>,
            children: (
              <Card 
                title="管理员操作历史" 
                extra={
                  <Space>
                    <Space.Compact style={{ width: 250 }}>
                      <Input
                        placeholder="搜索操作人/对象/详情/IP"
                        allowClear
                        onPressEnter={(e) => handleSearch((e.target as HTMLInputElement).value)}
                      />
                      <Button type="primary" icon={<SearchOutlined />} onClick={() => {}}>
                        搜索
                      </Button>
                    </Space.Compact>
                    <Select
                      placeholder="操作类型"
                      value={selectedOperationType}
                      onChange={setSelectedOperationType}
                      style={{ width: 120 }}
                    >
                      <Option value="all">全部类型</Option>
                      {Object.entries(operationTypeMap).map(([key, value]) => (
                        <Option key={key} value={key}>{value.label}</Option>
                      ))}
                    </Select>
                    <Select
                      placeholder="管理员"
                      value={selectedAdmin}
                      onChange={setSelectedAdmin}
                      style={{ width: 120 }}
                    >
                      <Option value="all">全部管理员</Option>
                      {admins.map(admin => (
                        <Option key={admin.id} value={admin.id.toString()}>{admin.name}</Option>
                      ))}
                    </Select>
                    <RangePicker onChange={handleDateRangeChange} placeholder={['开始日期', '结束日期']} />
                  </Space>
                }
              >
                <Table
                  columns={operationColumns}
                  dataSource={filteredOperations}
                  rowKey="id"
                  loading={loading}
                  pagination={{ pageSize: 10 }}
                  scroll={{ x: 1400 }}
                />
              </Card>
            ),
          },
          {
            key: '2',
            label: <span><LoginOutlined /> 登录日志</span>,
            children: (
              <Card 
                title="系统登录记录" 
                extra={
                  <Space>
                    <Space.Compact style={{ width: 250 }}>
                      <Input
                        placeholder="搜索管理员/IP/地点/原因"
                        allowClear
                        onPressEnter={(e) => handleSearch((e.target as HTMLInputElement).value)}
                      />
                      <Button type="primary" icon={<SearchOutlined />} onClick={() => {}}>
                        搜索
                      </Button>
                    </Space.Compact>
                    <Select
                      placeholder="登录结果"
                      value={selectedLoginResult}
                      onChange={setSelectedLoginResult}
                      style={{ width: 120 }}
                    >
                      <Option value="all">全部结果</Option>
                      {Object.entries(loginResultMap).map(([key, value]) => (
                        <Option key={key} value={key}>{value.label}</Option>
                      ))}
                    </Select>
                    <Select
                      placeholder="管理员"
                      value={selectedAdmin}
                      onChange={setSelectedAdmin}
                      style={{ width: 120 }}
                    >
                      <Option value="all">全部管理员</Option>
                      {admins.map(admin => (
                        <Option key={admin.id} value={admin.id.toString()}>{admin.name}</Option>
                      ))}
                    </Select>
                    <RangePicker onChange={handleLoginDateRangeChange} placeholder={['开始日期', '结束日期']} />
                  </Space>
                }
              >
                <Table
                  columns={loginLogColumns}
                  dataSource={filteredLoginLogs}
                  rowKey="id"
                  loading={loading}
                  pagination={{ pageSize: 10 }}
                  scroll={{ x: 1400 }}
                />
              </Card>
            ),
          },
          {
            key: '3',
            label: <span><SecurityScanOutlined /> 安全事件监控</span>,
            children: (
              <Card 
                title="系统安全事件"
                extra={
                  <Space>
                    <Space.Compact style={{ width: 250 }}>
                      <Input
                        placeholder="搜索事件/用户/资源/IP"
                        allowClear
                        onPressEnter={(e) => handleSearch((e.target as HTMLInputElement).value)}
                      />
                      <Button type="primary" icon={<SearchOutlined />} onClick={() => {}}>
                        搜索
                      </Button>
                    </Space.Compact>
                    <Select
                      placeholder="安全级别"
                      value={selectedSecurityLevel}
                      onChange={setSelectedSecurityLevel}
                      style={{ width: 120 }}
                    >
                      <Option value="all">全部级别</Option>
                      {Object.entries(securityLevelMap).map(([key, value]) => (
                        <Option key={key} value={key}>{value.label}</Option>
                      ))}
                    </Select>
                    <RangePicker onChange={handleSecurityDateRangeChange} placeholder={['开始日期', '结束日期']} />
                  </Space>
                }
              >
                <Table
                  columns={securityEventColumns}
                  dataSource={filteredSecurityEvents}
                  rowKey="id"
                  loading={loading}
                  pagination={{ pageSize: 10 }}
                  scroll={{ x: 1400 }}
                  onRow={(record) => ({
                    onClick: () => {
                      if (!record.isRead) {
                        handleMarkAsRead(record.id);
                      }
                    }
                  })}
                />
              </Card>
            ),
          },
        ]}
      />
    </div>
  );
};

export default LogManagement;
